package com.openxt.nbzj.call;

import android.content.Context;
import android.os.Handler;

import com.alibaba.fastjson.JSON;
import com.openxt.nbzj.event.Event;
import com.openxt.nbzj.event.EventManager;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.RemotingModel;
import com.openxt.nbzj.remoting.RemotingEx;
import com.openxt.nbzj.util.SystemUtil;

import com.alibaba.fastjson.JSONObject;
import qs.openxt.libs.util.StringUtil;

/**
 * Created by 颖杰_2 on 2016-07-28.
 * 3.3.1.1	心跳
 */
public class HeartBeatManager implements RemotingEx.OnActionListener {

    private static HeartBeatManager manager = null;
    private JSONObject DEV = null;
    private Handler mHandler = new Handler();
    private RemotingModel remotingModel = null;
    private boolean running = false;
    private int HeartBeatMinutes = 0;

    protected HeartBeatManager(){
    }

    public static HeartBeatManager instance(){
        if( manager == null )
            manager = new HeartBeatManager();
        return manager;
    }

    public void start(Context context, int HeartBeatMinutes){
        if(HeartBeatMinutes == 0)
            return;
        if(context != null)
            DEV = SystemUtil.getDevice(context);

        this.HeartBeatMinutes = HeartBeatMinutes;
        running = true;
        doHeart();
    }

    private void doHeart(){
        if(!running)
            return;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                doCall();
            }
        }, HeartBeatMinutes * 1000 * 60);
    }

    private void doCall(){
        remotingModel = new RemotingModel();
        remotingModel.doHeartbeatCall(this, false, DEV);
    }

    public void stop(){
        running = false;
    }

    @Override
    public void onActionCompleted(String reVal, String actionName) {
        try{
            JSONObject json = JSON.parseObject(reVal);
            String IsKickout = json.getString("IsKickout");
            if("true".equals(IsKickout)){//被踢出
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Event event = new Event(ConfigModel.APP_NOTIFIY_KICKOUT);
                            EventManager.instance().fireEvent(event);
                        }catch (Exception e){}
                    }
                }, 10);
                stop();
                return;
            }
            doHeart();
        }catch (Exception e){
            doHeart();
        }
    }

    @Override
    public void onActionFailed(String errorVal, String actionName) {
        doHeart();
    }
}
